package com.jack.xiaoer.web.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.base.Preconditions;
import com.jack.xiaoer.dto.ShopDTO;
import com.jack.xiaoer.entity.Shop;
import com.jack.xiaoer.service.ShopService;
import com.jack.xiaoer.util.AjaxResponse;
import com.jack.xiaoer.validator.Groups;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

/**
 * Created by Jackaroo Zhang on 2018/12/11.
 */
@Validated
@RestController
@RequestMapping("/shop")
public class ShopController extends BaseController {

    @Autowired
    private ShopService shopService;

    @GetMapping("/index/{pageNum}/{pageSize}")
    public AjaxResponse index(@PathVariable int pageNum, @PathVariable int pageSize) {
        Preconditions.checkArgument(pageNum > 0, "pageNum should be positive");
        Preconditions.checkArgument(pageSize > 0, "pageSize should be positive");

        IPage<Shop> shopPage = shopService.listShop(pageNum, pageSize);
        return AjaxResponse.success("获取商家列表成功", shopPage);
    }

    @GetMapping("/detail/{shopId}")
    public AjaxResponse getShop(@PathVariable Long shopId) {
        Preconditions.checkArgument((shopId != null && shopId > 0), "商家ID为空或者不合法");

        ShopDTO shopDetail = shopService.getShopDetail(shopId);

        if (shopDetail == null)
            return AjaxResponse.fail("查询不到该商家信息");

        return AjaxResponse.success("查询商家信息成功", shopDetail);
    }

    @PostMapping("/create")
    public AjaxResponse create(@RequestBody @Validated(Groups.ShopCreate.class) Optional<Shop> shop, BindingResult bindingResult) {
        AjaxResponse error = commonValidate(shop, bindingResult);
        if (null != error) {
            return error;
        }

        Shop data = shopService.createShop(shop);
        if (data == null) {
            return AjaxResponse.fail("创建商家失败");
        }
        return AjaxResponse.success("创建商家成功", data);
    }

    @ExceptionHandler({IllegalArgumentException.class})
    public AjaxResponse handleIllegalParamters(IllegalArgumentException e) {
        return AjaxResponse.invalid(e.getMessage());
    }

}
